<script setup>
import { ref } from "vue";
import TnInput from '@tuniao/tnui-vue3-uniapp/components/input/src/input.vue'
import TnRadio from '@tuniao/tnui-vue3-uniapp/components/radio/src/radio.vue'
import { get, post } from "@/request/request";
import { onShow } from "@dcloudio/uni-app";
import { config } from "@/config";


const money = ref('');
const wList = ref({});

const moneyForm = ref({
  money: '', //提现金额
  appMethod: '', //提现方式
  account: '', //提现账号
  remark: '', //备注
  img: '',//图片
  // bank: '', //开户行
});

const minMoney = ref(0);
const maxMoney = ref(0);


onShow(() => {
  wMethod();
  Wconf();
  getUserMy();
})

const wMethod = () => {
  get('/public_api/get_w_method').then(res => {
    const { data } = res;
    console.log('wMethod', data);
    wList.value = data;
  })
}



// 获取用户信息
const getUserMy = () => {
  get("/user_my", uni.getStorageSync("sessionKey")).then((res) => {
    const { data } = res;
    money.value = data.money;
  });
};

const selectItem = (id) => {
  moneyForm.value.appMethod = id;
  wList.value = wList.value.map(item => ({
    ...item,
    showInfo: item.id === id && (id === 3 || id === 4 || id === 5),
    inputs: item.id === id ? generateInputs(id) : []
  }));
};

const generateInputs = (id) => {
  switch (id) {
    case 3:
      return [
        { label: '姓名', type: 'text', value: '' },
        { label: '账号', type: 'number', value: '' }
      ];
    case 4:
      return [
        { label: '姓名', type: 'text', value: '' },
        { label: '账号', type: 'number', value: '' }
      ];
    case 5:
      return [
        { label: '开户人', type: 'text', value: '' },
        { label: '开户行', type: 'number', value: '' }
      ];
    default:
      return [];
  }
};

const printInputValue = (value, label) => {
  console.log(`输入框 ${label}: ${value}`);
  if (label === '开户人') {
    moneyForm.value.remark = value;
  }
  if (label === '开户行') {
    moneyForm.value.bank = value;
  }
  if (label === '姓名') {
    moneyForm.value.remark = value;
  }
  if (label === '账号') {
    moneyForm.value.account = value;
  }

};

const getBankCardInfo = (e) => {
  moneyForm.value.account = e.detail.value;
}
//图片上传
const actionUrl = config.baseUrl + '/public_api/upload'

// 图片上传处理函数
const uploadImage = () => {
  uni.chooseImage({
    count: 1, // 默认为9，设置为1表示只能选择一张图片
    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认两者都有
    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认两者都有
    success: (chooseImageRes) => {
      const imageSrc = chooseImageRes.tempFilePaths[0]; // 获取选择的图片路径

      uni.showLoading({
        title: '上传中'
      });

      uni.uploadFile({
        url: actionUrl,
        filePath: imageSrc,
        name: 'file',
        success: (uploadRes) => {
          const { data } = JSON.parse(uploadRes.data);
          console.log('dataimag', data);
          if (data && data.url) {
            moneyForm.value.img = data.url; // 更新图片URL
            console.log('上传成功:', data.url);
          }
          uni.hideLoading();
        },
        fail: (uploadErr) => {
          console.error('上传失败:', uploadErr);
          uni.hideLoading();
        }
      });
    },
    fail: () => {
      console.error('选择图片失败');
    }
  });
};

const allMoney = () => {
  moneyForm.value.money = money.value;
}

const changeAppMethod = (id) => {
  console.log('changeAppMethod', id);
  moneyForm.value.appMethod = id;
}


const Wconf = () => {
  get('/get_w_conf', { "sessionKey": uni.getStorageSync("sessionKey") }).then(res => {
    const { data } = res;
    console.log('Wconf', data);
    minMoney.value = data.min_money;
    maxMoney.value = data.max_money;
  }).catch(err => {
    console.error('获取配置失败:', err);
  });
};

const submitMoney = () => {
  // 验证必填参数
  const missingFields = [];
  if (!moneyForm.value.money) missingFields.push('提现金额');
  if (!moneyForm.value.appMethod) missingFields.push('提现方式');
  // if (!moneyForm.value.account) missingFields.push('提现账号');

  if (missingFields.length > 0) {
    uni.showToast({
      title: `请填写以下必填项: ${missingFields.join(', ')}`,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 验证提现金额是否在允许范围内
  const money = parseFloat(moneyForm.value.money);
  if (money < minMoney.value) {
    uni.showToast({
      title: `提现金额不能低于 ${minMoney.value} 元`,
      icon: 'none',
      duration: 2000
    });
    return;
  }
  if (money > maxMoney.value) {
    uni.showToast({
      title: `提现金额不能高于 ${maxMoney.value} 元`,
      icon: 'none',
      duration: 2000
    });
    return;
  }

  console.log('提交数据:', moneyForm.value);
  post('/withdrawal', moneyForm.value, { "Content-Type": "application/x-www-form-urlencoded", sessionKey: uni.getStorageSync("sessionKey") })
    .then(res => {
      const { data } = res;
      console.log('提交成功:', data);
    })
    .catch(err => {
      console.error('提交失败:', err);
      uni.showToast({
        title: '提交失败，请稍后重试',
        icon: 'none',
        duration: 2000
      });
    });
};
</script>

<template>
  <view class="payouts">
    <view class="top-box"></view>
    <view class="person-box">
      <view style="font-size: 32rpx;">可提现金额：{{ money }}元</view>
      <view class="pay-money">
        <view class="pay-money-item">
          <view class="money-icon">¥</view>
          <TnInput type="number" v-model="moneyForm.money" placeholder="请输入提现金额" :border="false" />
        </view>
        <view class="all-money" @click="allMoney">全部</view>
      </view>
    </view>
    <view class="content-title">
      <text>提现金额不能小于{{ minMoney }}元</text>
      <text>提现需要加收1%手续费</text>
    </view>
    <view class="title">提现方式</view>
    <template v-for="(item, index) in wList" :key="index">
      <view class="wechat-ck" @click="selectItem(item.id)">
        <view class="wechat">
          <image :src="config.baseUrl + '/file/' + item.img" />
          <text>{{ item.name }}</text>
        </view>
        <view style="margin-right: 30rpx">
          <TnRadio active-color="#0052D9" v-model="moneyForm.appMethod" :label="item.id"
            @change="changeAppMethod(item.id)" />
        </view>
      </view>
      <view v-if="item.showInfo" class="additional-info">
        <template v-for="(input, idx) in item.inputs" :key="idx">
          <view style="display: flex;justify-content: space-around;align-items: center;">
            <view class="label">{{ input.label }}</view>
            <input class="input" :type="input.type" v-model="input.value" :placeholder="input.label"
              @blur="printInputValue(input.value, input.label)" />
          </view>
        </template>
        <view v-if="item.id === 5">
          <view style="display: flex;justify-content: space-around;align-items: center;">
            <view class="label">账号</view>
            <input class="input" type="text" placeholder="银行卡账号" v-model="moneyForm.account" @blur="getBankCardInfo">
          </view>
        </view>
        <view v-if="item.id === 3 || item.id === 4">
          <text>收款码</text>
          <view class="upload-img">
            <view v-if="!moneyForm.img" class="upload-img-item" @click="uploadImage">
              <view>+</view>
            </view>
            <image v-else class="upload-img-item" :src="config.baseUrl + '/file/' + moneyForm.img" />
          </view>
        </view>
      </view>
    </template>
    <view class="submit-btn">
      <view class="submit-btn-item" @click="submitMoney">提交</view>
    </view>
  </view>
</template>

<style scoped lang="scss">
.payouts {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .top-box {
    width: 100%;
    height: 240rpx;
    background: #0052D9;
  }

  .person-box {
    margin-top: -200rpx;
    width: 686rpx;
    height: 184rpx;
    background: #fff;
    border-radius: 18rpx;
    padding: 20rpx;
    display: flex;
    justify-content: space-around;
    flex-direction: column;

    .pay-money {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .pay-money-item {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .money-icon {
          color: #0052D9;
          font-size: 32rpx;
        }
      }

      .all-money {
        height: 100%;
        //width: 48rpx;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .content-title {
    margin-top: 20rpx;
    width: 686rpx;
    height: 80rpx;
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    color: rgba(0, 0, 0, 0.6);
  }

  .title {
    width: 100%;
    padding: 30rpx;
    font-size: 32rpx;
    color: rgba(0, 0, 0, 0.9);
    font-weight: 600;
  }

  .wechat-ck {
    margin-top: 20rpx;
    width: 686rpx;
    background: rgba(255, 255, 255, 1);
    height: 112rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-radius: 12rpx;

    .wechat {
      margin-left: 20rpx;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-around;

      image {
        width: 48rpx;
        height: 48rpx;
      }

      text {
        margin: 20rpx;
        font-size: 32rpx;
      }
    }


  }

  .additional-info {
    width: 686rpx;
    margin-top: -12rpx;
    background-color: #fff;
    padding: 20rpx;
    border-bottom-right-radius: 20rpx;
    border-bottom-left-radius: 20rpx;

    .label {
      width: 30%;
      height: 112rpx;
      display: flex;
      align-items: center;
      border-bottom: 2rpx solid #E5E5E5;
    }

    .input {
      width: 70%;
      height: 112rpx;
      display: flex;
      align-items: center;
      border-bottom: 2rpx solid #E5E5E5;
    }

    .upload-img {
      width: 100%;
      padding: 20rpx;

      .upload-img-item {
        font-size: 40rpx;
        width: 160rpx;
        height: 160rpx;
        background: #f3f3f3;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 10rpx;
      }
    }
  }

  .submit-btn {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 190rpx;
    background: #FFF;
    display: flex;
    align-items: center;
    justify-content: center;
    padding-bottom: env(safe-area-inset-bottom);

    .submit-btn-item {
      width: 686rpx;
      height: 96rpx;
      background: #0052D9;
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 12rpx;
    }
  }
}
</style>
